﻿using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Domain
{
    /// <summary>
    /// 权限表
    /// </summary>
    [SuppressChangedListener]
    public class PermissionInfo : IEntity, IEntityTypeBuilder<PermissionInfo>
    {
        public PermissionInfo()
        {
            Roles = new HashSet<RoleInfo>();
            Users = new HashSet<UserInfo>();
            ParentPaths = new string[0];
        }

        /// <summary>
        /// 权限代码
        /// </summary>
        [MaxLength(200), Required]
        public string Code { get; set; }

        /// <summary>
        /// 权限名称
        /// </summary>
        [MaxLength(200), Required]
        public string Name { get; set; }

        /// <summary>
        /// 父级节点路径
        /// </summary>
        [MaxLength(400)]
        public string[] ParentPaths { get; set; }

        /// <summary>
        /// 权限类型
        /// </summary>
        public PermissionType Type { get; set; }
        /// <summary>
        /// 父级代码
        /// </summary>
        [MaxLength(200)]
        public string ParentCode { get; set; }
        /// <summary>
        /// 依赖资源id
        /// </summary>
        [MaxLength(400)]
        public string DependentResources { get; set; }
        /// <summary>
        /// 父对象
        /// </summary>
        public virtual PermissionInfo Parent { get; set; }
        /// <summary>
        /// 子集合
        /// </summary>
        public virtual ICollection<PermissionInfo> Children { get; set; }

        /// <summary>
        /// 权限赋予的角色集合
        /// </summary>
        public virtual ICollection<RoleInfo> Roles { get; set; }

        /// <summary>
        /// 权限赋予的用户集合
        /// </summary>
        public virtual ICollection<UserInfo> Users { get; set; }

        public void Configure(EntityTypeBuilder<PermissionInfo> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.UseDefaultTableNameDefine();

            entityBuilder.HasKey(p => p.Code);

            entityBuilder.HasIndex(i => i.Code);

            // 递归外键,必须启用查询跟踪才能正常使用
            entityBuilder.HasMany(p => p.Children)
                .WithOne(p => p.Parent)
                .HasForeignKey(f => f.ParentCode, false)
                .OnDelete(DeleteBehavior.ClientSetNull);

            entityBuilder.Property(p => p.ParentPaths)
                .HasConversion(v => string.Join("/", v), v => v.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries));
        }
    }
}
